const path = require('path');
const fs = require('fs-extra');
const { sh } = require('tasksfile');
const concurrently = require('concurrently');
const { existsDirSync } = require('../../taskutils');

class TaskMap {
    /**
     * 生产模式构建
     *
     * 输出到 src/jsLib/service
     */
    build() {
        sh('webpack --mode production --config ./build/index.js');
    }

    /**
     * 开发模式构建
     *
     * 输出到 dist/jsLib/service
     */
    dev() {
        const fromPath = path.resolve(__dirname, '..', 'jsLib/service/index.js');

        const toDir = path.resolve(__dirname, '..', '..', 'dist/jsLib/service');
        const result = existsDirSync(toDir, { create: true });

        if (result) {
            const toPath = path.resolve(toDir, 'index.js');
            fs.copyFileSync(fromPath, toPath);

            concurrently([
                'webpack --watch --mode development --config ./build/index.js',
                'cross-env SERVICE_PORT=9876 SERVICE_MODE=dev nodemon --experimental-wasm-threads ../../dist/jsLib/service/index.js',
            ]);
        } else {
            console.error('目录不存在');
        }
    }
}

function run() {
    const args = process.argv;
    if (args && args.length >= 2) {
        const taskMap = new TaskMap();
        const argArray = args.slice(2);
        const [task] = argArray;
        taskMap[task]();
    }
}

run();
